package com.xq.security;

import com.xq.entity.SecurityUser;
import com.xq.entity.UmsUsers;
import com.xq.service.IUmsUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 主要实现了一个获取用户的接口
 * 获取用户的信息封装到userDetails后交割springSecurity管理
 * 由此可知springSecurity只是一个简化了登录注册的框架
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private IUmsUsersService iUmsUsersService;

    /**
     * 根据用户名去查找用户信息
     * 如果用户不存在的话则抛出异常
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UmsUsers user = iUmsUsersService.getUserByUsername(username);
        if (user == null) {throw new UsernameNotFoundException("用户不存在");}
        SecurityUser securityUser = new SecurityUser();
        securityUser.setId(user.getUserId());
        securityUser.setUsername(user.getUsername());
        securityUser.setPassword(user.getPasswordHash());
        return securityUser;
    }

    /**
     * 根据用户名去查找用户信息
     * 如果用户不存在的话则抛出异常
     * @param
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException {
        UmsUsers user = iUmsUsersService.getUserByPhone(phone);
        if (user == null) {throw new UsernameNotFoundException("用户不存在");}
        SecurityUser securityUser = new SecurityUser();
        securityUser.setId(user.getUserId());
        securityUser.setUsername(user.getUsername());
        securityUser.setPassword(user.getPasswordHash());
        return securityUser;
    }


}
